package com.gaoyi.crm.control;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.gaoyi.crm.R;
import com.gaoyi.crm.databinding.ViewDateSelectBinding;
import com.gaoyi.crm.util.DateUtil;

import java.util.Calendar;
import java.util.Date;

public class DateSelectView extends BaseView<ViewDateSelectBinding> {

    private String mFormat;
    private Calendar mCalendar;

    public DateSelectView(@NonNull Context context) {
        super(context);
    }

    public DateSelectView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public DateSelectView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public DateSelectView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void initView(TypedArray ta) {
        mFormat = ta.getString(R.styleable.DateSelectView_date_select_format);
        String title = ta.getString(R.styleable.DateSelectView_date_select_title);
        mBinding.tvDateTitle.setText(title);
        mCalendar = Calendar.getInstance();
        mBinding.tvSelectDate.setOnClickListener(view -> showDatePicker());
    }

    private void showDatePicker() {
        DateUtil.showDatePicker(mContext, mFormat, mCalendar, (date) -> {
            mBinding.tvSelectDate.setText(DateUtil.DateTimeToStr(date, mFormat));
            mCalendar.setTime(date);
        });
    }

    @Override
    protected ViewDateSelectBinding getViewBinding() {
        return ViewDateSelectBinding.inflate(LayoutInflater.from(mContext));
    }

    public void setDate(Date date) {
        mCalendar.setTime(date);
        mBinding.tvSelectDate.setText(DateUtil.DateTimeToStr(date, mFormat));
    }

    /**
     * 设置date前几年日期
     */
    public void setDate(Date date, int yearBefore) {
        mCalendar.setTime(date);
        mCalendar.set(Calendar.YEAR, mCalendar.get(Calendar.YEAR) - yearBefore);
        mBinding.tvSelectDate.setText(DateUtil.DateTimeToStr(mCalendar.getTime(), mFormat));
    }

    public String getDate(){
        return DateUtil.DateTimeToStr(mCalendar.getTime(),mFormat);
    }

    @Override
    protected int[] getAttrs() {
        return R.styleable.DateSelectView;
    }

}
